﻿using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
using MusicExplorer.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MusicExplorer.Repository.Interfaces;
using System.Globalization;
using MusicExplorer.Repository.Internals;
using System.Net;

namespace MusicExplorer.Repository
{
    [Id("263CD9AC-46B8-4887-A9F5-1C9D5D0FD7AA")]
    public sealed class WorldOfHouseRepository : RepositoryBase, ITracksByGenre
    {
        private const string m_websiteUrl = @"http://www.worldofhouse.es";

        public WorldOfHouseRepository(Model.Repository repository)
            : base(repository)
        {
            m_urlAllEntities[EntityType.Genre] = m_websiteUrl;
            m_urlTracks[new QueryDefinition(QueryType.AllTracks, EntityType.Genre)]
                = m_websiteUrl + @"/genre/{0}/page/{1}/tab/filter_paginator";
        }

        public override int StartingPage { get { return 1; } }
        public override bool IsMusicStore { get { return false; } }

        protected override List<Track> DecodeTracks(QueryType type, Entity entity, string source)
        {
            var document = new HtmlDocument();
            document.LoadHtml(source);
            var page = document.DocumentNode;

            var tracks = new List<Track>();
            var listNode = page.QuerySelector("#pagi_main_filter_paginator");
            foreach (var trackNode in listNode.ChildNodes.Where(n => n.Name == "div"))
            {
                var link = trackNode.QuerySelector("a");
                var id = link.Attributes["href"].Value.Split('/')[1];
                var track = new Track(id, m_repository, TrackType.Classic);
                var date = trackNode.QuerySelector(".date > .text");
                track.PublishDate = DateTime.ParseExact(date.InnerText, "dd/MMM/yy", new CultureInfo("en-US"));
                track.Name = WebUtility.HtmlDecode(link.InnerText);
                track.Mp3 = string.Format(@"{0}/mp3/streaming/{1}.mp3",
                    m_websiteUrl, track.Id);
                track.Url = m_websiteUrl + "/" + link.Attributes["href"].Value;
                var img = trackNode.QuerySelector(".image > img");
                var data = img.Attributes["data-original"].Value;
                if (data == @"/images/default_cover.jpg")
                {
                    track.Artwork = string.Format(@"{0}{1}", m_websiteUrl, data).Replace("80_80", "296_296");
                }
                else
                {
                    track.Artwork = data;
                }
                tracks.Add(track);
            }
            return tracks;
        }

        protected override List<Genre> DecodeGenres(string source)
        {
            var document = new HtmlDocument();
            document.LoadHtml(source);
            var page = document.DocumentNode;

            var genres = new List<Genre>();

            // 1. Chargement des genres généraux
            var menuNode = page.QuerySelector("#genre_menu");
            var allGenresNodes = menuNode.QuerySelectorAll("[id^='genre_menu_']");
            foreach (var genreNode in allGenresNodes)
            {
                var linkNode = genreNode.QuerySelector("a");
                var classNode = genreNode.QuerySelector(".genre_menu_item");
                var id = linkNode.Attributes["href"].Value.Split('/')[1];
                var name = WebUtility.HtmlDecode(classNode.InnerText);
                var genre = new Genre(id, name, m_repository);
                genres.Add(genre);
            }

            // 2. Chargement des sous genres
            //var subMenuNode = page.QuerySelector("#genres_menu_list");
            //var subMenuGroupNodes = subMenuNode.QuerySelectorAll("td");
            //foreach (var subMenuGroupNode in subMenuGroupNodes)
            //{
            //    foreach (var subGenreNode in subMenuGroupNode.ChildNodes.Where(n => n.Name == "div"))
            //    {
            //        var linkNode = subGenreNode.QuerySelector("a");
            //        var id = linkNode.Attributes["href"].Value.Split('/')[1];
            //        var name = linkNode.InnerText;
            //        var genre = new Genre(id, name, m_repository);
            //        genres.Add(genre);
            //    }
            //}

            return genres;
        }
    }
}
